// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: xguo

#pragma once

#include <memory>
#include <sstream>
#include <string>
#include <utility>

#include "coin2/exchange/base/order/rate_tracker.h"

namespace coin2::exchange::dydx_v3::api_util {

class DydxRateTracker : public coin2::exchange::base::order::IRateTracker {
 public:
  using RateTracker = coin2::exchange::base::order::RateTracker;
  using ActionType = coin2::exchange::base::order::IRateTracker::ActionType;
  using RateLimitReportWriter = coin2::exchange::base::order::RateLimitReportWriter;
  using FixedWindowRateTracker = coin2::exchange::base::order::FixedWindowRateTracker;

 public:
  explicit DydxRateTracker(
      const MarketExchangeApi& mea,
      const coin2::exchange::order::OrderConnectionConfig& cfg);

  void SetRateLimitInfo(int32_t rate_limit, int32_t rate_limit_remaining) override { CHECK(false); }
  void Push(int32_t num_reqs, int64_t timestamp, ActionType action_type) override;
  bool HasEnoughRateLimit(int64_t timestamp, ActionType action_type) override;
  void SetNativeSymbol(const std::string&);

  void ParseRateLimitInfo(const std::shared_ptr<AsioHttpContext>&, ActionType) override {}
  void SetRateLimitInfoString(const google::protobuf::Message* message) override;
  void WriteRateLimitReportMessage(OrderLoggerCB callback) override;
  void UpdateRateLimitInfo(const std::string&);
  double GetMaxRateUsedRatio(int64_t timestamp, ActionType action_type) override;

 private:
  using RateTrackerType = std::unique_ptr<FixedWindowRateTracker>;

  RateTrackerType& GetOrderRateTracker(const std::string&);
  RateTrackerType& GetCancelRateTracker(const std::string&);

  RateTrackerType req_rate_tracker_;

  std::unordered_map<std::string, RateTrackerType> order_rate_tracker_;
  std::unordered_map<std::string, RateTrackerType> cancel_rate_tracker_;

  std::unique_ptr<RateLimitReportWriter> rate_limit_report_writer_;
  coin2::exchange::order::RateLimitInfoFuturesDydx rate_config_;
  std::string native_symbol_;
};

}  // namespace coin2::exchange::dydx_v3::api_util
